import Axios from 'axios'
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token:null,
    userInfo:null,
    cartList:[],
    iscart:false
  },
  mutations: {
    saveToken(state,payload){
      state.token = payload
      localStorage.setItem('token',JSON.stringify(payload))
    },
    saveUserInfo(state,payload){
      state.userInfo=payload;
      //JSON.stringfy 把对象或数组转化为字符串
      localStorage.setItem("userInfo",JSON.stringify(payload));
    },
    saveCart(state,payload){
      if ( 
        JSON.stringify(state.cartList).indexOf(
           JSON.stringify(payload)
         ) == -1
       ) {
         console.log( state.cartList);
        state.cartList.unshift(payload)
       } 
      localStorage.setItem("saveCart",JSON.stringify(state.cartList));
    },
    delCart(state,payload){
      state.cartList=payload
    }
  },
  actions: {
    async getuserinfo(context){
     await axios(
        {
          method: "GET",
          url: `http://47.115.51.185/api/user`,
          headers: {
            "Authori-zation": "Bearer " + context.state.token
          }
        }
        ).then(res=>{
        console.log(res.data);
        context.commit('saveUserInfo',res)
      }).catch(err=>{
        console.log(err);
      })
    }
  },
  modules: {
  }
})
